package com.superhelper.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    private static SpringContextUtil self;

    private boolean test;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        String[] profiles = context.getEnvironment().getActiveProfiles();
        if (profiles.length >= 1) {
            test = StringUtils.equalsIgnoreCase(profiles[0], "test");
        } else {
            test = false;
        }
        self = this;
    }

    public <T> T getBean(Class<T> type) {
        return context.getBean(type);
    }

    public Object getBean(String beanId) {
        return context.getBean(beanId);
    }

    public static Object getBeanStatic(String beanId) {
        return context.getBean(beanId);
    }

    public boolean isTest() {
        return test;
    }

    public static boolean isOnline() {
        return !test();
    }

    public static boolean test() {
        return self.isTest();
    }

}
